package game.gui;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.*;

import game.model.Block;

/**
 * @author Aqilah
 * Class BlockPanel displays a block in the board
 */
public class BlockPanel extends JPanel{
	private Block block;
	public static final int BLOCK_SIZE = 100;
	private Image image;
	private static Image backImage = null;
	private MainFrame mainFrame;
	
	/** Constructor */
	public BlockPanel(MainFrame mainFrame, Block block){
		this.mainFrame = mainFrame;
		this.block = block;
				
		Toolkit toolkit = Toolkit.getDefaultToolkit();
        image = toolkit.createImage(block.getImagePath());
        image = image.getScaledInstance(BLOCK_SIZE, BLOCK_SIZE, Image.SCALE_FAST);
        
        // get back image
		if (backImage == null){
			backImage = toolkit.createImage(BlockPanel.class.getResource("../images/back.png"));
			image = image.getScaledInstance(BLOCK_SIZE, BLOCK_SIZE, Image.SCALE_FAST);
		}
		
		// add click listener
		addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				handleClick();
			}			
		});
	}
		
	/** Handle mouse click */
	protected void handleClick() {
		if (!block.isRemoved())
			mainFrame.handleClick(block.getRow(), block.getColumn());
	}

	/** Override - Return the preferred size of this block */
	public Dimension getPreferredSize(){
		return new Dimension(BLOCK_SIZE, BLOCK_SIZE);
	}
	
	/** Override paintComponent method - draw the block */
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		
		// only draw image if the block is not removed
		if (!block.isRemoved()){						
			if (block.isTurnedOn()){
				g.drawImage(image, 0, 0, this);			
			}
			else{
				g.drawImage(backImage, 0, 0, this);
			}
		}		
	}	

}
